package shuntianfu.com.shuntianfucompressor;

import android.content.Intent;
import android.provider.ContactsContract;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import business.MainManager;
import common.AppContext;
import common.Constants;
import model.Compressor;
import model.StoreInfoModel;
import service.MyServiceOne;
import ui.LoadingProgressDialog;
import utils.CustomToast;
import utils.DataHandler;

public class HomeActivity extends AppCompatActivity {

    private static final String TAG = "HomeActivity";

    private GridView gridView;
    private TextView refresh;

    private List<StoreInfoModel> data;

    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        startService(new Intent(this, MyServiceOne.class));

        showCustomProgrssDialog();

        initView();
        initData();
    }

    private void initData() {
        data = new ArrayList();
        adapter = new MyAdapter();

        getStoreList();

    }

    private void getStoreList() {

        MainManager.getInstance().getStoreList(this, new DataHandler() {
            @Override
            public void onData(int code, String msg, Object obj) {
                hideCustomProgressDialog();
                if (code == Constants.SERVER_SUCCESS) {
                    utils.Log.e(TAG, obj.toString());

                    Type listType = new TypeToken<List<StoreInfoModel>>() {
                    }.getType();
                    Gson gson = new Gson();
                    if (data.size() != 0) {
                        data.clear();
                    }
                    data = gson.fromJson(obj.toString(), listType);
                    Log.d(TAG, data.toString());
                    gridView.setAdapter(adapter);
                } else {
                    CustomToast.showToast(HomeActivity.this, "数据获取失败，点击店面按钮刷新", 2000);
                }
            }
        });
    }

    private void initView() {
        gridView = (GridView) findViewById(R.id.gv_shuntianfu_supermarket);
        refresh = (TextView) findViewById(R.id.tv_chaoshi_list);

        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomProgrssDialog();
                getStoreList();
            }
        });

        gridView.setOnItemClickListener(gridViewClickListener);

    }

    AdapterView.OnItemClickListener gridViewClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

//            Intent intent = new Intent(HomeActivity.this, CompressListActiviy.class);
			Intent intent = new Intent(HomeActivity.this, MainActivity.class);

//			Bundle bundle = new Bundle();
//            bundle.putSerializable("STOREINFO",data.get(position));
//            intent.putExtras(bundle);
			AppContext.getInstance().setStoreInfoModel(data.get(position));


			startActivity(intent);
            HomeActivity.this.overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
        }
    };


    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            MyViewHolder holder = null;
            if (null == convertView) {
                holder = new MyViewHolder();
                convertView = LayoutInflater.from(HomeActivity.this).inflate(R.layout.item_supermarkert_list, null);

                holder.tvName = (TextView) convertView.findViewById(R.id.tv_sp_name);
                holder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_sp_icon);
                convertView.setTag(holder);
            } else {
                holder = (MyViewHolder) convertView.getTag();
            }

            StoreInfoModel storeInfoModel = data.get(position);

            if (null != storeInfoModel.getName()) {
                holder.tvName.setText(storeInfoModel.getName());
            }

            return convertView;
        }
    }


    class MyViewHolder {

        TextView tvName;
        ImageView ivIcon;

    }


    private long lastBackKeyTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if ((System.currentTimeMillis() - lastBackKeyTime) > 2000) {
                Log.e("TAG", "System.currentTimeMillis()==" + System.currentTimeMillis() + "lastBackKeyTime==" + lastBackKeyTime);
                Log.e("TAG", "System.currentTimeMillis() - lastBackKeyTime" + (System.currentTimeMillis() - lastBackKeyTime));
                CustomToast.showToast(this, "再按一次退出应用", 1000);
                lastBackKeyTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }


        return super.onKeyDown(keyCode, event);
    }


    protected LoadingProgressDialog loadingProgressDialog;

    public void showCustomProgrssDialog() {

        if (null == loadingProgressDialog)

            loadingProgressDialog = LoadingProgressDialog.createDialog(this);

        loadingProgressDialog.setCanceledOnTouchOutside(false);//点击无效，回退有效

//        loadingProgressDialog.setCancelable(false);//点击无效，回退无效

    }

    public void hideCustomProgressDialog() {

        if (null != loadingProgressDialog) {

            loadingProgressDialog.dismiss();

            loadingProgressDialog = null;

        }

    }
}
